define(['jquery', 'select2','datetimepicker','mapController',"controller","rights","moment","coordtransform","mapview"], function ($) {

    var c = require("controller");
    var rights = require("rights");
    var mapController = require("mapController");
    var coordtransform = require("coordtransform");
    var  moment= require("moment");
    var mapview = require("mapview");
    var tHeight = $(window).height() - 50 - 35;
    $(".content").height(tHeight);



    return {
        init: function () {
            // test set token
            // localStorage.setItem('token', 'MiMxNDcyNjk0Mjk4QGcuZmx5LWNsb3VkLmNuI1pjZDYzQ2tqeXg1MzdHSkRQWU43SEkxUS9Ecz0=');
            this.searchData={};
            this.initDataTable();
            this.bindEvent();
        },
        dataTable: null,
        delRow:null,
        searchData:{},
        initDataTable: function () {
            var self = this;
            this.dataTable = c.myDataTable($("#mmg"), {
                ajax: function (data, callback, settings) {
                    //封装请求参数
                    var param = {
                        page_no: (data.start / data.length),
                        page_size: data.length,
                        state: 1
                    };
                    $.extend(true,param,self.searchData);
                    //ajax请求数据
                    c.ajax({
                        url: "plan/search",
                        cache: false, //禁用缓存
                        data: param, //传入组装的参数
                        dataType: "json",
                        success: function (result) {
                            //封装返回数据
                            $.each(result.plans,function (i,row) {
                                var space= JSON.parse(row.space);
                                row.sid=space.id;
                                row.sName=space.name;
                                var pilots=row.pilots.split(',');
                                row.pName=[];
                                self.pilots=result.pilots;
                                $.each(result.pilots,function (pi,pilot) { //获取 飞行员名称

                                    if($.inArray(pilot.id,pilots)!=-1){
                                        row.pName.push(pilot.name);
                                    }

                                });
                                row.pName=row.pName.join(',');

                                var fids=row.fids.split(',');
                                row.fName=[];
                                self.models=result.models;
                                $.each(result.models,function (pi,model) {//获取 飞行器 型号

                                    if($.inArray(model.fid,fids)!=-1){
                                        row.fName.push(model.model);
                                    }
                                });
                                row.fName=row.fName.join(',');



                            });
                            var returnData = {};
                            returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                            returnData.recordsTotal = result.count;//返回数据全部记录
                            returnData.recordsFiltered = result.count;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = result.plans;//返回的数据列表
                            //console.log(returnData);
                            //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                            //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                            callback(returnData);
                        }
                    });
                },
                scrollY: (tHeight - 210) + "px",
                scrollCollapse: true,
                columns: [
                    {"data": "id"},
                    {"data": "space"},
                    {"data": "cid"},
                    {"data": "fids"},
                    {"data": "fName"},
                    {"data": "pName"},
                    {"data": "takeoff"},
                    {"data": "landing"},
                    {"data": "batch_num"},
                    {"data": "height"}
                ],
                columnDefs: [
                    {
                        "targets": 0,//
                        "data": "id",
                        "render": function (data, type, row) {
                            return moment(row.takeoff,'X').format('YYYYMMDD')+'-'+c.getCompanys(row.cid,'short')+'-'+data;
                        }
                    },
                    {
                        "targets": 1,//
                        "data": "space",
                        "render": function (data, type, row) {
                            space = JSON.parse(row.space);
                            return space.name;
                        }
                    },
                    {
                        "targets": 2,//所在公司列
                        "data": "cid",
                        "render": function (data, type, row) {
                            return c.getCompanys(row.cid);
                        }
                    },
                    {
                        "targets": 6,//起飞时间
                        "data": "takeoff",
                        "render": function (data, type, row) {
                            return c.formatDateWithoutSFromInt(row.takeoff);
                        }
                    },
                    {
                        "targets": 7,//着陆时间
                        "data": "landing",
                        "render": function (data, type, row) {
                            return c.formatDateWithoutSFromInt(row.landing);
                        }
                    },
                    {
                        // 定义操作列,######以下是重点########
                        "targets": 10,
                        "data": 'state',
                        "render": function (data, type, row) {
                            var html = "<div class='btn-group'>" +
                                "<a href='#' class='btn btn-sm btn-info see'><i class='fa fa-eye'></i>审核</a>" +
                                "</div>";
                            return html;
                        }
                    }],
                drawCallback: function(settings, json) {
                    rights.isShowFn($('.content'));
                }
            });
        },
        bindEvent: function () {
            var self = this;
            var dataSee = '';
            $('#mmg').on('click', '.see', function () {
                //审核
                var dataRow = self.dataTable.row( $(this).parents('tr') ).data();
                $("#myModal>.modal-dialog").load("plans/view.html", function(){
                    $("#myModal").modal('show');

                    self.formInit(dataRow);

                });
            }).on('click', 'tr', function () {
                $(this).siblings().removeClass("select");
                $(this).toggleClass("select");
            });


            $('#search').on('click',function () {
                self.searchData={
                    name:$('#searchUserName').val(),
                    no:$('#searchNo').val()
                };
                self.dataTable.draw();
            });



        },

        formInit:function (dataRow) {
            var self=this;
            var $form = $('.edit-form',$('#myModal'));

            if(dataRow){//判断是否编辑
                $form.find('[name="id"]').val(dataRow.id);
                $form.find('[name="cid"]').val(c.getCompanys(dataRow.cid));
                $form.find('[name="sid"]').val(dataRow.sName);
                $form.find('[name="fids"]').val(dataRow.fids);
                $form.find('#fid_type').val(dataRow.fName);

                $form.find('[name="pilots"]').val(dataRow.pName);
                $form.find('[name="takeoff"]').val(moment(dataRow.takeoff,'X').format('YYYY-MM-DD HH:mm'));
                $form.find('[name="landing"]').val(moment(dataRow.landing,'X').format('YYYY-MM-DD HH:mm'));
                $form.find('[name="batch_num"]').val(dataRow.batch_num);
                $form.find('[name="height"]').val(dataRow.height);
                $form.find('[name="remark"]').val(dataRow.remark);
                $('.modal-title').text('审核飞行计划');
            }


            //地图展示飞行要素
            $('#show_element').on('click',function () {
                $("#mapModal>.modal-dialog").load("element/mapview.html", function(){
                    $("#mapModal").modal("show");

                    c.ajax({
                        url: 'spaceline/detail',
                        dataType: "json",
                        cache: false,
                        data: {
                            cid:dataRow.cid,
                            id:dataRow.sid
                        },
                        success: function (res) {
                            if (res.err == 0) {
                                var elements=res.spaceline.elements;
                                elements=typeof elements=="string"?JSON.parse(elements):elements;
                                mapview.init(elements);
                            }
                        }
                    });

                });
            });

            $("#show_element").after("<a href='#' class='btn btn-sm btn-danger reject'>拒绝</a>");
            $(".reject").before("<a href='#' class='btn btn-sm btn-primary approve'>通过</a>");
            var html='<div class="form-group"><label class="col-sm-3 control-label">拒绝理由</label><div class="col-sm-8"><input id="reason" class="form-control"  type="text" /></div></div>';
            $('.modal-footer').before(html);
            $('.approve').on('click', function () {
                c.confirm({
                    title:"提示信息",
                    content:'是否通过',
                    confirm:function () {

                        c.ajax({
                            url: 'plan/approve',
                            dataType: "json",
                            cache: false,
                            data: {
                                id: dataRow.id
                            },
                            success: function (res) {
                                $('#myModal').modal('hide');
                                if (res.err < 0) {
                                    return;
                                }
                                self.dataTable.ajax.reload();
                            }
                        });

                    }
                })
            })
            $('.reject').on('click', function () {
                    //拒绝
                    c.confirm({
                        title:"提示信息",
                        content:'是否拒绝',
                        confirm:function () {
                            var reason = $('#reason').val();
                            if(reason==""){
                                c.alert({
                                    centent:'请填写拒绝理由'
                                });
                                return false;
                            }
                            c.ajax({
                                url: 'plan/reject',
                                dataType: "json",
                                cache: false,
                                data: {
                                    id: dataRow.id,
                                    reason:reason
                                },
                                success: function (res) {
                                    if (res.err == 0) {
                                        $('#myModal').modal('hide');
                                        self.dataTable.ajax.reload();
                                    }
                                }
                            });

                        }
                    })
                });



        }
    }
});



